﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Data.SqlServer
{
    /// <summary>
    /// 
    /// </summary>
    public class SqlServerDataCommand : DataCommand
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cmdTxt"></param>
        /// <param name="cmdType"></param>
        /// <param name="database"></param>
        public SqlServerDataCommand(string name, string cmdTxt, CommandType cmdType, Database database) : base(name, cmdTxt, cmdType, database)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sortFields"></param>
        /// <returns></returns>
        protected override string CreateCommandTextForPagedQuery(int pageIndex, int pageSize, IDictionary<string, bool> sortFields)
        {
            string mainSql = this.CommandText;

            int startRowIndex = (pageIndex - 1) * pageSize + 1;
            int endRowIndex = pageIndex * pageSize;
            string sortStatement = DatabaseUtil.ResolveSortExpression(sortFields);
            string sql = $"SELECT * FROM(SELECT *,Row_Number() OVER({sortStatement}) AS RowNo FROM({mainSql})TM)TP WHERE RowNo>={startRowIndex} AND RowNo<={endRowIndex}";
            return sql;
        }
    }
}
